﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using WPS.Code.Code;
using WPS.Code.Utils;
using WPS.Log;
using WPS.Model;

namespace WPS.Web.Controllers
{
    public class FileController : ApiController
    {
        #region 获取文件列表
        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("weboffice/list")]
        public JsonResult<Response> GetFileList()
        {
            LogHelper.Info("进入weboffice/list");
            try
            {
                string token = string.Empty;
                WPSUserInfo userInfo = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["token"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "token为空."));
                }
                token = request["token"].ToString();
                userInfo = CacheUtils.Get<WPSUserInfo>(token);
                if (userInfo == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到相关的用户信息."));
                }
                JObject jsonObject = new JObject();
                using (WPSModel context = new WPSModel())
                {
                    IEnumerable<WPSFileInfo> files = context.WPSFileInfo;//.Where(f => f.CREATOR == userInfo.ID);
                    if (files != null && files.Any())
                    {
                        JArray jArray = new JArray();
                        DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                        foreach (WPSFileInfo file in files)
                        {
                            JObject fileObj = new JObject();
                            fileObj["id"] = file.ID;
                            fileObj["name"] = file.NAME;
                            fileObj["ext"] = WPSFileUtils.GetFileExt(file.NAME);
                            fileObj["size"] = file.SIZE;
                            fileObj["create_date"] = file.CREATE_DATE;
                            fileObj["download_url"] = file.DOWNLOAD_URL;
                            jArray.Add(fileObj);
                        }
                        jsonObject["list"] = jArray;
                    }
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, jsonObject, ""));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, ex.Message));
            }
        }
        #endregion

        #region 上传文件
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("weboffice/upload")]
        public JsonResult<Response> FileUpload()
        {
            LogHelper.Info("进入weboffice/upload");
            try
            {
                string token = string.Empty;
                WPSUserInfo userInfo = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["token"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "token为空."));
                }
                token = request["token"].ToString();
                userInfo = CacheUtils.Get<WPSUserInfo>(token);
                if (userInfo == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到相关的用户信息."));
                }
                if (request.Files.Count > 0)
                {
                    HttpPostedFileBase file = request.Files[0];
                    string fileName = file.FileName;
                    string ext = WPSFileUtils.GetFileExt(fileName);
                    string fileId = Guid.NewGuid().ToString();
                    string filePath = HttpContext.Current.Server.MapPath("~/") + "Files\\" + fileId + "." + ext;
                    file.SaveAs(filePath);
                    WPSFileInfo fileModel = new WPSFileInfo();
                    fileModel.ID = fileId;
                    fileModel.NAME = fileName;
                    fileModel.SIZE = file.ContentLength;
                    fileModel.CREATOR = userInfo.ID;
                    fileModel.CREATE_DATE = DateTime.Now;
                    fileModel.VERSION = 1;
                    fileModel.DOWNLOAD_URL = WPSConfig.Download_Host + "/weboffice/getFile?fileId=" + fileId;
                    using (WPSModel context = new WPSModel())
                    {
                        context.WPSFileInfo.Add(fileModel);
                        context.SaveChanges();
                        JObject jsonObject = new JObject();
                        jsonObject["code"] = "1";
                        jsonObject["msg"] = "";
                        JObject fileObj = new JObject();
                        fileObj["id"] = fileModel.ID;
                        fileObj["name"] = fileModel.NAME;
                        fileObj["size"] = fileModel.SIZE;
                        fileObj["ext"] = ext;
                        fileObj["create_date"] = fileModel.CREATE_DATE;
                        fileObj["download_url"] = fileModel.DOWNLOAD_URL;
                        jsonObject["data"] = fileObj;
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, jsonObject, ""));
                    }
                }
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "上传失败，找不到文件."));
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, ex.Message));
            }
        }
        #endregion

        #region 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("weboffice/delete")]
        public JsonResult<Response> DeleteFile()
        {
            LogHelper.Info("进入weboffice/delete");
            try
            {
                string fileId = string.Empty;
                string token = string.Empty;
                string ext = string.Empty;
                WPSFileInfo fileModel = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["token"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "token为空."));
                }
                token = request["token"].ToString();
                if (request["fileId"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "fileId为空."));
                }
                fileId = request["fileId"].ToString();
                using (WPSModel context = new WPSModel())
                {
                    fileModel = context.WPSFileInfo.Where(f => f.ID == fileId).FirstOrDefault();
                    if (fileModel == null)
                    {
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到该文件信息"));
                    }
                    if (fileModel.NAME.LastIndexOf(".") > -1)
                    {
                        ext = fileModel.NAME.Substring(fileModel.NAME.LastIndexOf(".") + 1);
                    }
                    context.WPSFileInfo.Remove(fileModel);
                    context.SaveChanges();
                    string filePath = HttpContext.Current.Server.MapPath("~/") + "Files\\" + fileId + "." + ext;
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, fileModel.ID, "删除成功"));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, ex.Message));
            }
        }
        #endregion

        #region 获取图片文件信息
        /// <summary>
        /// 获取图片文件信息
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("weboffice/picture")]
        public JsonResult<Response> GetPicture()
        {
            LogHelper.Info("进入weboffice/url");
            try
            {
                string fileId = string.Empty;
                string token = string.Empty;
                string ext = string.Empty;
                WPSFileInfo fileModel = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["token"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "token为空."));
                }
                token = request["token"].ToString();
                if (request["fileId"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "fileId为空."));
                }
                fileId = request["fileId"].ToString();
                using (WPSModel context = new WPSModel())
                {
                    fileModel = context.WPSFileInfo.Where(f => f.ID == fileId).FirstOrDefault();
                    if (fileModel == null)
                    {
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到该文件信息"));
                    }
                    ext = WPSFileUtils.GetFileExt(fileModel.NAME);
                    if (ext == "")
                    {
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "ext为空."));
                    }
                    if (WPSFileUtils.PictureExt.Contains(ext)) //图片相关
                    {
                        JObject jsonObject = new JObject();
                        jsonObject["id"] = fileModel.ID;
                        jsonObject["name"] = fileModel.NAME;
                        jsonObject["url"] = "http://" + Request.RequestUri.Authority + "/Files/" + fileModel.ID + "." + ext;
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, jsonObject, ""));
                    }
                    else
                    {
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "图片格式不合法"));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, ex.Message));
            }
        }
        #endregion

        #region  获取文件路径（wps）
        /// <summary>
        /// 获取文件路径（wps）
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("weboffice/url")]
        public JsonResult<Response> GetFileUrl()
        {
            LogHelper.Info("进入weboffice/url");
            try
            {
                string fileId = string.Empty;
                string token = string.Empty;
                string ext = string.Empty;
                string userId = string.Empty;
                WPSFileInfo fileModel = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["token"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "token为空."));
                }
                token = request["token"].ToString();
                if (request["fileId"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "fileId为空."));
                }
                fileId = request["fileId"].ToString();
                if (request["userId"] != null)
                {
                    userId = request["userId"].ToString();
                }

                using (WPSModel context = new WPSModel())
                {
                    fileModel = context.WPSFileInfo.Where(f => f.ID == fileId).FirstOrDefault();
                    if (fileModel == null)
                    {
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "找不到该文件信息"));
                    }
                    ext = WPSFileUtils.GetFileExt(fileModel.NAME);
                    if (ext == "")
                    {
                        return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "ext为空."));
                    }

                    string permission = "read";
                    string url = WPSConfig.Domain + "/office";
                    if (ext == "xls" || ext == "xlsx")
                    {
                        url += "/s/";
                    }
                    else if (ext == "ppt" || ext == "pptx")
                    {
                        url += "/p/";
                    }
                    else if (ext == "pdf")
                    {
                        url += "/f/";
                    }
                    else
                    {
                        url += "/w/";
                    }
                    url += fileId + "?";
                    string param = "_w_appid=" + WPSConfig.AppId + "&_w_fid=" + fileId + "&" + ApiUtils.Token + "=" + token+"&_w_userid="+ userId;
                    if (request["permission"] != null)//读写权限
                    {
                        permission = request["permission"].ToString();
                    }
                    param += "&_w_permission=" + permission;
                    String signature = WpsUtils.getSignature(WpsUtils.paramToMap(param), WPSConfig.AppKey);
                    url += param + "&_w_signature=" + signature;
                    JObject obj = new JObject
                    {
                        ["url"] = url,
                        ["token"] = token
                    };
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, obj, ""));

                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message);
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, ex.Message));
            }
        }
        #endregion

        #region 新建文档（wps）
        /// <summary>
        /// 新建文档（wps）
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("weboffice/new")]
        public JsonResult<Response> NewFile()
        {
            try
            {
                LogHelper.Info("进入weboffice/new");
                string token = string.Empty;
                string userId = string.Empty;
                WPSUserInfo userInfo = null;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "MS_HttpContext参数为null."));
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["token"] == null)
                {
                    return Json<Response>(ApiUtils.DoResponse(ResponseCode.Fail, null, "token为空."));
                }
                if (request["_w_userid"] != null)
                {
                    userId = request["userId"].ToString();
                    LogHelper.Info("userid：" + userId);
                }
                
                token = request["token"].ToString();
                userInfo = CacheUtils.Get<WPSUserInfo>(token);
                if (userInfo == null && !string.IsNullOrEmpty(userId))
                {
                    using (WPSModel context = new WPSModel())
                    {
                        userInfo = context.WPSUserInfo.Where(u => u.ID == userId).FirstOrDefault();
                    }
                }
                JObject obj = new JObject();
                string param = "_w_appid=" + WPSConfig.AppId;
                param += "&" + ApiUtils.Token + "=" + token + "&_w_user_id=" + userInfo.ID;
                String signature = WpsUtils.getSignature(WpsUtils.paramToMap(param), WPSConfig.AppKey);
                string url = WPSConfig.Domain + "/office/w/new/0?";
                url += param + "&_w_signature=" + signature;
                obj["redirect_url"] = url;
                obj["token"] = token;
                LogHelper.Info("redirect_url：" + url);
                LogHelper.Info("离开weboffice/new");
                return Json<Response>(ApiUtils.DoResponse(ResponseCode.Success, obj, ""));
            }
            catch (Exception e)
            {
                LogHelper.Error(e.Message);
            }
            return null;
        }
        #endregion

        #region 下载文件
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("weboffice/getFile")]
        public HttpResponseMessage DownLoadFile()
        {
            LogHelper.Info("进入weboffice/getFile");
            try
            {
                string fileId = string.Empty;
                int version = 1;
                HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];
                if (httpContextBase == null)
                {
                    return null;
                }
                HttpRequestBase request = httpContextBase.Request;
                if (request["fileId"]==null)
                {
                    return null;
                }
                fileId = request["fileId"].ToString();
                if (request["version"] != null)
                {
                    version = Convert.ToInt32(request["version"]);
                }
                LogHelper.Info("fileId：" + fileId + ";version：" + version.ToString());
                if (string.IsNullOrEmpty(fileId))
                {
                    return null;
                }
                WPSFileInfo fileModel = null;
                using (WPSModel context = new WPSModel())
                {
                    fileModel = context.WPSFileInfo.Where(f => f.ID == fileId).FirstOrDefault();
                }
                if (fileModel == null)
                {
                    return null;
                }
                string ext = WPSFileUtils.GetFileExt(fileModel.NAME);
                string fileName = fileModel.ID;
                if (version>1)
                {
                    fileName += "_v" + version.ToString();
                }
                string filePath = HttpContext.Current.Server.MapPath("~/") + "Files\\" + fileName + "."+ ext;
                LogHelper.Info("filePath：" + filePath);
                System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = HttpUtility.UrlEncode(fileModel.NAME)
                };
                response.Headers.Add("Access-Control-Expose-Headers", "FileId");
                response.Headers.Add("FileId", HttpUtility.UrlEncode(fileModel.ID));
                LogHelper.Info("离开weboffice/getFile");
                return response;
            }
            catch (Exception ex)
            {
                LogHelper.Error("weboffice/getFile：" + ex.Message+"<br>"+ex.StackTrace);
            }
            return null;
        }
        #endregion

    }
}
